package com.free.bsf.eureka.client.limitrate;

import com.free.bsf.core.base.BsfException;
import com.free.bsf.core.util.ReflectionUtils;
import lombok.val;

import java.lang.reflect.Method;

public class KeyExpression {
    private String key;
    private Method callMethod;
    public KeyExpression(String key){
        this.key = key;
        parseKey(key);
    }

    private void parseKey(String key){
        try {
            if (key.startsWith("@@")) {
                String key2 = key.replace("@@", "");
                val args = key2.split("::");
                String cls = args[0];
                String method = args[1];
                val findCls = ReflectionUtils.tryClassForName(cls);
                callMethod = ReflectionUtils.findMethod(findCls, method);
            }
        }catch (Exception e){
            throw new BsfException("限流key表达式解析失败,找不到方法;key="+key,e);
        }
    }

    public String parse(String className,String methodName){
        try {
            if (callMethod!=null) {
                if(callMethod.getParameterCount()==2) {
                    return (String) callMethod.invoke(null, new Object[]{className, methodName});
                }else if(callMethod.getParameterCount()==1){
                    return (String) callMethod.invoke(null, new Object[]{className});
                }else{
                    return (String) callMethod.invoke(null, new Object[]{});
                }
            } else {
                return key;
            }
        }
        catch (Exception e){
            throw new BsfException("限流key表达式解析失败,找不到方法;key="+key,e);
        }

    }

    public static String example(String className,String methodName){
        return className+"."+methodName;
    }
}
